import paho.mqtt.client as mqtt
import os
import json
import streamlit as st
_print = print
print = st.write

# MQTT配置
MQTT_BROKER = os.getenv('MQTT_BROKER', 'broker.emqx.io')
MQTT_PORT = int(os.getenv('MQTT_PORT', 1883))
MQTT_CLIENT_ID = os.getenv('MQTT_CLIENT_ID', 'pi_timelapse_trigger')

TOPIC_CAMERA_STATUS = os.getenv('TOPIC_CAMERA_STATUS', "pi/camera/status")
TOPIC_SNAPSHOT = os.getenv('TOPIC_SNAPSHOT', "pi/camera/snapshot")


class MqttTrigger:
    def __init__(self):
        self.client = mqtt.Client(client_id=f"{MQTT_CLIENT_ID}_sender")
        self.client.on_connect = self.on_connect
        self.client.on_publish = self.on_publish
        self.client.on_message = self.on_message
        self.client.subscribe(TOPIC_CAMERA_STATUS)
        self.topic_handlers = {
            TOPIC_CAMERA_STATUS: self.handle_camera_status,
        }

    def handle_camera_status(self, msg):
        """处理相机状态消息"""
        _print(f"Received camera status message: {msg.payload.decode()}")
        print(f"Received camera status message: {msg.payload.decode()}")
        st.image(msg.payload.decode())
        self.client.disconnect()

    def on_connect(self, client, userdata, flags, rc):
        """MQTT连接回调"""
        if rc == 0:
            print("Connected to MQTT broker")
        else:
            print(f"Failed to connect to MQTT broker with code: {rc}")

    def on_message(self, client, userdata, msg):
        """MQTT消息接收回调"""
        _print(f"Received message: {msg.payload.decode()}")
        print(f"Received message: {msg.payload.decode()}")
        topic = msg.topic
        if topic in self.topic_handlers:
            self.topic_handlers[topic](msg)
        else:
            print(f"Unknown topic: {topic}")

    def on_publish(self, client, userdata, mid):
        """发布消息回调"""
        print(f"Message published with mid: {mid}")
        # self.client.disconnect()
        pass

    def send_snapshot_command(self):
        """发送控制命令"""
        try:
            self.client.connect(MQTT_BROKER, MQTT_PORT, 60)
            payload = json.dumps({"command": "snapshot"})
            self.client.publish(TOPIC_SNAPSHOT, payload, qos=1)
            self.client.loop_forever()
        except Exception as e:
            print(f"Failed to send command: {str(e)}")


if __name__ == "__main__":
    import streamlit as st
    st.write("发送拍照命令")
    if st.button("拍照"):
        mqtt_trigger = MqttTrigger()
        mqtt_trigger.send_snapshot_command()  # 发送拍照命令
